import { showToast } from "../../utils/asyncWx.js";
import { request } from "../../request/index.js";


// pages/pay/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addr: {},
    checkedCart: [],
    totalNum: 0,
    totalPrice: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const addr = wx.getStorageSync("addr");
    const cart = wx.getStorageSync("cart");
    // 过滤出选中的商品, filter: 创建新数组存入满足条件项
    let checkedCart = cart.filter(v => v.checked);
    let totalPrice = 0;
    let totalNum = 0;
    checkedCart.forEach(v => {
      totalPrice += v.num * v.goods_price;
      totalNum += v.num;
    });
    this.setData({
      addr, checkedCart, totalPrice, totalNum
    })
  },

  // TODO 由于是个人开发者没有商户号, 无法实现支付功能, 暂时用提示代替
  // 点击支付
  async handleOrderPay () {
    try {
      // 1. 判断缓存中有无用户token
      const token = wx.getStorageSync("token");
      if (!token) {
        wx.navigateTo({
          url: '/pages/auth/index',
        });
      }
      // 2. 创建订单 获取订单编号
      // 2.1 准备订单api请求头参数, 优化了request后不需要手动准备请求头
      // const header = { Authorization: token };
      // 2.2 请求体参数
      const order_price = this.data.totalPrice;
      const consignee_addr = this.data.addr.all;
      const { checkedCart } = this.data;
      let goods = [];
      checkedCart.forEach(v => goods.push({
        goods_id: v.goods_id,
        goods_num: v.num,
        goods_price: v.goods_price
      }));
      const orderParams = { order_price, consignee_addr, goods };
      // 3. 获取订单编号
      const { order_number } = await request({ url: '/my/orders/create', data: orderParams, method: 'POST' });
      // TODO 由于获取token失败,所以无法创建订单
      console.log(order_number);
      // 4. 发起预支付接口
      const { pay } = await request({ url: '/my/orders/req_unifiedorder', data: { order_number }, method: 'POST' })
      // console.log(res2);
      // 5. 发起微信支付
      await requestPayment(pay);
      // 6. 查询订单状态
      const res = await request({ url: "/my/orders/chkOrder", data: { order_number }, method: 'POST' })
      await showToast({ title: '支付成功!' })
      // 7. 手动删除缓存中已付款的商品
      let newCart = wx.getStorageSync("cart");
      newCart = newCart.filter(v => !v.checked);
      wx.setStorageSync("cart", newCart);
      //  支付成功, 跳转到订单页面
      wx.navigateTo({
        url: '/pages/order/index'
      });
    } catch (error) {
      await showToast({ title: '暂时无法创建订单!' })
      console.log(error);
    }
  }
})